package com.viknix.threadpool.manager.config.util;

import com.viknix.threadpool.manager.common.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: Dongqi
 * @Date: 2021/11/1 9:42
 * @Version 1.0
 * @Description: HttpUtil
 */
@Slf4j
public class HttpUtil {

    private static final String X_REAL_IP = "X-Real-IP";
    private static final String X_FORWARDED_FOR = "X-Forwarded-For";
    private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ",";

    public static String getRemoteIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader(X_FORWARDED_FOR);
        if (StringUtils.isNotBlank(xForwardedFor)) {
            return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim();
        }
        String nginxHeader = request.getHeader(X_REAL_IP);
        return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
    }

    public static void generateResponse(HttpServletResponse response, List<String> changedGroups) {
        if (!CollectionUtils.isEmpty(changedGroups)) {
            try {
                // 将所有的 GroupKeys 拼接起来写回
                String changedGroupKeStr = Md5Util.compareMd5ResultString(changedGroups);
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Cache-Control", "no-cache,no-store");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write(changedGroupKeStr);
            } catch (Exception ex) {
                log.error(ex.toString(), ex);
            }
        }
    }

    public static void generateAsyncResponse(AsyncContext asyncContext, List<String> changedGroups) {
        // 如果没有变更的配置，直接返回
        if (null == changedGroups) {
            // Tell web container to send http response.
            asyncContext.complete();
            return;
        }

        // 如果有变更的配置，将变更的配置写回
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

        try {
            String respStr = Md5Util.compareMd5ResultString(changedGroups);
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache,no-store");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(respStr);
            asyncContext.complete();
        } catch (Exception ex) {
            log.error(ex.toString(), ex);
            asyncContext.complete();
        }
    }
}
